package com.yenlien.traceyun.usercenter.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.common.crypt.CryptUtil;
import com.yenlien.traceyun.common.utils.RedisUtils;
import com.yenlien.traceyun.usercenter.dao.CompanyDao;
import com.yenlien.traceyun.usercenter.dao.DepartmentDao;
import com.yenlien.traceyun.usercenter.dao.UserDao;
import com.yenlien.traceyun.usercenter.entity.User;
import com.yenlien.traceyun.usercenter.service.UserService;
import com.yenlien.traceyun.webase.controller.BaseController;
import com.yenlien.traceyun.webase.utils.CheckParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-03-04
 * @description:
 **/
@Slf4j
@RestController
@RequestMapping(value = "/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private DepartmentDao departmentDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private CompanyDao companyDao;

    @Autowired
    private RedisUtils redisUtils;

    @Value("${login.appid}")
    private String appId;

    @Value("${login.appsecret}")
    private String appSecret;

    /**
     * 用户注册
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Object register(User user, HttpServletRequest request) throws Exception {
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        CheckParams.checkBean(user, new String[]{"username"});
//        User user = userInfo.toJavaObject(User.class);
        return success(userService.save(user, files));
    }

    @RequestMapping(value = "/save2", method = RequestMethod.POST)
    public Object register2(@RequestBody User user) throws Exception {
        CheckParams.checkBean(user, new String[]{"username"});
//        User user = userInfo.toJavaObject(User.class);
        return success(userService.save2(user));
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Object update(User user, HttpServletRequest request) throws Exception {
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        CheckParams.checkBean(user, new String[]{"id"});
        userService.update(user, files);
        return success("success");
    }


    @RequestMapping(value = "/update2", method = RequestMethod.POST)
    public Object update2(@RequestBody User user) throws Exception {
        CheckParams.checkBean(user, new String[]{"id"});
        userService.update2(user);
        return success("success");
    }


    /**
     * 根据id加载用户
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/findById/{id}", method = RequestMethod.GET)
    public Object load(@PathVariable("id") String id) {
        return success(userService.findById(id));
    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
//        map.put("id", "265f1c4a821f4794a80f4bf497e8cb6f");
        map.put("timestamp", "2023-09-14 10:59:11");
        map.put("delFlag", 1);
        Object data = map; //原始数据
        String toSign = JSON.toJSONString(data);//此处采用fastjson转换为字符串，即提的待签名交数据
        //同步用户数据
        String digestHex = SecureUtil.hmacSha1("k-S-aPekYJmMUn1nHHqGrp2lVenxLtAg-OH2Oo__n6xB3nuiy-OoS0n9G5cycz4PzntdFz")
                .digestHex(toSign);
        String result = HttpRequest.post("http://182.132.59.143:8084/api/open/user/list?pageNum=1&pageSize=100")
                .header("app_id", "64f5647ab7602ddeb282a3f7")
                .header("signature", digestHex)
                .body(toSign, "application/json")
                .timeout(30000)
                .execute()
                .body();
        //根据部门id获取用户部门信息
//        String digestHex = SecureUtil.hmacSha1("k-S-aPekYJmMUn1nHHqGrp2lVenxLtAg-OH2Oo__n6xB3nuiy-OoS0n9G5cycz4PzntdFz")
//                .digestHex(toSign);
//        String result = HttpRequest.post("http://182.132.59.143:8084/api/open/dept/list")
//                .header("app_id", "64f5647ab7602ddeb282a3f7")
//                .header("signature", digestHex)
//                .body(toSign, "application/json")
//                .timeout(30000)
//                .execute()
//                .body();
        //访问系统登录地址
        HttpRequest.get("http://182.132.59.143:8083/api/oauth/authorize?scope=read write profile email phone address&response_type=code&state=52378542395&client_id=64f5647ab7602ddeb282a3f7&redirect_uri=http://zyzy.cpzsyun.com/api/medicine/readMdb/getAccessToken");


        System.out.println(result);
    }

    @GetMapping("/loginV1")
    public JSONObject loginV1(String userId){
        return userService.loginV1(userId);
    }
    /**
     * 登录授权
     *
     * @param userInfo ：{"uid":"email|phone|username","password":"密码","appid":"应用id"}
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Object login(@RequestBody JSONObject userInfo) {
        CheckParams.checkJson(userInfo, new String[]{"uid", "password", "appid"});
        return userService.login(userInfo.getString("uid"), userInfo.getString("password"), userInfo.getString("appid"));
    }

    @GetMapping(value = "/findCountByCompanyId/{companyId}")
    public Object findCountByCompanyId(@PathVariable("companyId") String companyId) {
        return success(userService.findCountByCompanyId(companyId));
    }

    @RequestMapping(value = "/findByList", method = RequestMethod.POST)
    public Object findByList(@RequestBody User user) {
        Page<User> page = userService.search(user);
        User companyCount = userDao.findCompanyCount(user.getCompanyId());
        JSONObject result = new JSONObject();
        result.put("code", "200");
        result.put("total", page.getTotalElements());
        result.put("rows", page.getContent());
        result.put("companyCount", companyCount);
        return result;
    }


    @RequestMapping(value = "/findByAll", method = RequestMethod.POST)
    public Object findByAll(@RequestBody JSONObject param) {
        CheckParams.checkJson(param, new String[]{"companyId"});
        return success(userService.findByAll(param));
    }

    @RequestMapping(value = "/checkPassword", method = RequestMethod.POST)
    public Object checkPassword(@RequestBody JSONObject param) {
        CheckParams.checkJson(param, new String[]{"userId", "password"});
        return success(userService.checkPassword(param));
    }

    @PostMapping(value = "/locked")
    public Object locked(@RequestBody JSONObject param) {
        CheckParams.checkJson(param, new String[]{"id", "locked"});
        userService.lockUser(param.getString("id"), param.getBoolean("locked"));
        return success("ok");
    }


    /**
     * 重置密码
     */
    @PostMapping(value = "/resetpassword")
    public Object resetPassword(@RequestBody JSONObject param) {
        CheckParams.checkJson(param, new String[]{"userId", "password"});
        userService.resetPassword(param.getString("userId"), param.getString("password"));
        return success("ok");
    }

    /**
     * 修改密码
     */
    @PostMapping(value = "/changepassword")
    public Object changepassword(@RequestBody JSONObject param) {
        CheckParams.checkJson(param, new String[]{"userId", "password", "oldp"});
        User user = userDao.findById(param.getString("userId"));
        if (!user.getPassword().equals(CryptUtil.md5(param.getString("oldp")))) {
            return success("false");
        }
        userService.resetPassword(param.getString("userId"), param.getString("password"));
        return success("ok");
    }

    /**
     * 导入
     *
     * @param
     * @return
     */
    @PostMapping(value = "/import")
    public Object importUsers(@RequestBody JSONArray jsonArray) {
        List<User> users = jsonArray.toJavaList(User.class);
        User user = users.get(0);
        String companyId = user.getCompanyId();
        List<User> inquire = userService.inquire(users, companyId);
        userDao.saveAll(inquire);
        return success(inquire.size());
    }

    /**
     * 查询新增的用户
     *
     * @return
     */
    @PostMapping("/newUsers")
    public Object newUsers() {
        return success(userService.newUsers());
    }

    /**
     * 查询累计的用户
     *
     * @return
     */
    @PostMapping("/cumUsers")
    public Object cumUsers() {
        return success(userService.cumUsers());
    }

    /**
     * 查询生产监管用户数量
     *
     * @return
     */
    @PostMapping("/numUser")
    public Object numUser(@RequestBody JSONObject param) {
        String companyId = param.getString("companyId");
        return success(userService.numUser(companyId));
    }

    /**
     * 查询生产监管用户数量
     *
     * @return
     */
    @PostMapping("/userNum")
    public Object userNum(@RequestBody JSONObject param) {
        String companyId = param.getString("companyId");
        if (!StringUtils.isEmpty(companyId)) {
            return success(userService.userNum(companyId));
        }
        return fail("companyId不能为空");
    }

    @PostMapping("/findByCompanyId")
    public Object findByCompanyId(@RequestBody JSONObject param) {
        if (param.get("companyId") != null) {
            String companyId = param.getString("companyId");
            List<User> byCompanyId = userService.findByCompanyId(companyId);
            JSONObject json = new JSONObject();
            json.put("CompanyObj", byCompanyId);
            return json;
        }
        return fail("companyId不能为null");
    }

    /**
     * 普惠金融：为银行创建登陆账户
     */
    @PostMapping("/saveUserAndCompany")
    public Object saveUserAndCompany(@RequestBody JSONObject param) {
        JSONObject obj = new JSONObject();
        obj.put("companyId", userService.insetUserAndCompany(param));
        return obj;
    }
}
